// 本地路由菜单加载器

import { get, has } from 'lodash-es'
import { BasicRouteItem } from './index.type'

export function routeLoader() {
  const routeModules = import.meta.glob('./modules/*.tsx', { eager: true })
  const menuData: BasicRouteItem[] = []
  try {
    for (const key in routeModules) {
      if (has(routeModules, key)) {
        const childRoutes = get(routeModules, `${key}`) as Record<string, any>
        Array.prototype.push.apply(menuData, childRoutes['routes'])
      }
    }
    const filterMenu = transformMenuData(menuData)
    return filterMenu
  } catch (err) {
    console.error(err)
    return menuData
  }
}

function transformMenuData(menuList: BasicRouteItem[]) {
  return menuList.filter((item) => {
    const children = item.routes
    if (children && children.length > 0) {
      item.routes = transformMenuData(children)
    }

    return item.isShow && !item.isEnabled
  })
}

export const localMenuData = routeLoader()
